<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      label-position="left"
    >
      <div style="padding-bottom: 5%">
        为给您提供更精准的服务，请补充以下信息
      </div>
      <el-form-item label="公司名称" prop="enterpriseName">
        <el-input
          v-model.trim="formData.enterpriseName"
          placeholder="请输入公司名称"
        />
      </el-form-item>
      <el-form-item label="您的姓名" prop="username">
        <el-input
          v-model.trim="formData.username"
          placeholder="请输入您的姓名"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model.trim="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div style="display: flex; flex-wrap: nowrap">
          <el-input
            v-model.trim="formData.code"
            placeholder="请输入验证码"
            style="width: 220px"
          />
          <el-button
            type="primary"
            :disabled="isSending || countdown > 0"
            @click="sendCode"
            style="margin-left: 10%"
          >
            {{ countdown > 0 ? `${countdown}秒后重试` : "发送验证码" }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="" prop="demand" label-width="0">
        <el-input
          v-model.trim="formData.demand"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="请输入您的需求，我们会在第一时间联系您"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, defineExpose } from "vue";
import { ElMessage } from "element-plus";
import { service } from "@/config/service";
import { useRouter } from "vue-router";
const router = useRouter();
const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref("立即体验"); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  enterpriseName: "",
  username: "",
  phone: "",
  demand: "",
  code: "",
  service: null,
});
const validatePhoneNumber = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/;
  if (!value) {
    return callback(new Error("手机号码不能为空"));
  }
  if (!reg.test(value)) {
    return callback(new Error("请输入正确的手机号码"));
  }
  callback();
};
const formRules = reactive({
  enterpriseName: [
    { required: true, message: "公司名称不能为空", trigger: "blur" },
  ],
  username: [{ required: true, message: "您的姓名不能为空", trigger: "blur" }],
  phone: [{ required: true, validator: validatePhoneNumber, trigger: "blur" }],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});
const formRef = ref(); // 表单 Ref

/** 打开弹窗 */
const opendialog = async (service) => {
  resetForm();
  dialogVisible.value = true;
  isSending.value = false;
  formData.value.service = service;
};
defineExpose({ opendialog }); // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    enterpriseName: "",
    username: "",
    phone: "",
    demand: "",
    code: "",
    service: null,
  };
  formRef.value?.resetFields();
};
let system = "";
if (location.hostname.indexOf("geovisearth") != -1) {
  system = `${location.origin}/work/`;
} else if (location.hostname.indexOf("139") != -1) {
  system = `${location.origin}/work/`;
} else {
  system = `http://${location.hostname}:18081/work/`;
}
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return;
  const valid = await formRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = await service.post("/orderManage/addOrder", formData.value);
    if (data.code === 200) {
      ElMessage({
        message: "信息已提交，请等待工作人员与您联系！",
        type: "success",
      });
      dialogVisible.value = false;
      formLoading.value = false;
      window.open(`${system}#/order/myOrder?ssoCheck=true`,'_blank')
    }
  } finally {
    formLoading.value = false;
  }
};

const isSending = ref(false);
const countdown = ref(0);
const sendCode = async () => {
  if (!formData.value.phone) {
    ElMessage({ message: "未填写手机号", type: "error" });
    return;
  }
  const data = await service.get(
    "https://api.geovisearth.com/passport/auth/sendSmsCode",
    {
      params: {
        appkey: "E21219DF60CD41EDB2DFF30B04FF7C6E",
        phone: formData.value.phone,
      },
    }
  );
  if (data.Data === "短信验证码发送成功,有效期:300s") {
    isSending.value = true;
    startCountdown();
  }
};
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isSending.value = false;
    }
  }, 1000);
};
</script>
